<?php
declare (strict_types = 1);

namespace app;

use catcher\CatchResponse;
use think\App;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Lang;
use think\Request;
use think\Response;
use think\Validate;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {}

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }


    /**
     * 操作成功返回的数据
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为1
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
     * @return void
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
         $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为0
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
     * @return void
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为0
     * @param string $type 输出类型，支持json/xml/jsonp
     * @param array $header 发送的 Header 信息
     * @return void
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => $this->request->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('route.var_jsonp_handler')) ? 'jsonp' : 'json');
        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = in_array($code,[0,1,102,400,401])? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        $response->send();
       // throw new HttpResponseException($response);
    }

    /**
     * 微信接口数据返回
     * @param $data
     * @param bool $error_code_range
     * @param callable $callback
     */
    protected function wxResult($data,$error_code_range = false,callable $callback = null){
        if(0 !== $data['errcode']){
            $code = 0;
            $error_msg = $data['errmsg'];
            if($error_code_range){
                $error_msg = $this->parseWxErrMsg($error_code_range,$data['errcode']);
                if(85088 == $data['errcode']){
                    $code = 102;
                }
            }
            //$this->error($error_msg,$data,$code);
            return CatchResponse::fail($error_msg,$code);
        }else{
            unset($data['errcode'],$data['errmsg']);
            is_callable($callback) && call_user_func_array($callback, [&$data]);
            //$this->success('ok',$data);
            return CatchResponse::success($data);
        }
    }

    /**
     * @param $error_code_range
     * @param $err_code
     * @return string
     */
    protected function parseWxErrMsg($error_code_range,$err_code){
        $_path = $this->app->getRootPath().'vendor'.DIRECTORY_SEPARATOR.'uctoo'.DIRECTORY_SEPARATOR.'think-easywechat'.DIRECTORY_SEPARATOR.'src'.DIRECTORY_SEPARATOR.'WxErrorCode'.DIRECTORY_SEPARATOR.$error_code_range.'.php';
        if(is_file($_path)){
            $lang = include $_path;
        }
        return $lang[$err_code] ?? '';
    }
}
